import { Button, Text, View, ScrollView, Image, StyleSheet } from 'react-native';
import React, { useRef, useState } from 'react';
import { Camera, useCameraDevice, useCameraFormat, useCameraPermission, TakePhotoOptions } from 'react-native-vision-camera';

type PathTestCase = {
  id: number;
  title: string;
  description: string;
  options: TakePhotoOptions;
  expected: 'SUCCESS' | 'FAILURE';
};

type TestResult = {
  test: PathTestCase;
  result: string;
  photo?: {
    path: string;
    width: number;
    height: number;
  };
};

export function TakePhotoOptionTest() {
  const [cameraPosition, setCameraPosition] = useState<'back' | 'front'>('front');
  const device = useCameraDevice(cameraPosition);
  const format = useCameraFormat(device, [
    { videoResolution: { width: 3048, height: 2160 } },
    { fps: 60 },
  ]);
  const { hasPermission, requestPermission } = useCameraPermission();
  const camera = useRef<Camera>(null);
  const [activeTest, setActiveTest] = useState<PathTestCase | null>(null);
  const [currentResult, setCurrentResult] = useState<TestResult | null>(null);
  const [isMirrored, setIsMirrored] = useState(false);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);

  if (!device) return <Text>No Camera Device Found</Text>;
  if (!hasPermission) requestPermission();

  const testCases: PathTestCase[] = [
    {
      id: 1,
      title: "1. 默认路径",
      description: "不提供path参数，使用系统临时目录",
      options: {},
      expected: 'SUCCESS'
    },
    {
      id: 2,
      title: "2. 绝对目录路径",
      description: "传入绝对目录路径（需真实存在）\n示例：/data/storage/el2/base/haps/entry/files/",
      options: { path: "/data/storage/el2/base/haps/entry/files/" },
      expected: 'SUCCESS'
    },
    {
      id: 3,
      title: "3. 传入沙箱不存在的路径",
      description: "传入不存在的路径",
      options: { path: "/data/storage/el2/base/1122334455667788" },
      expected: 'SUCCESS'
    },
    {
      id: 4,
      title: "4. 文件路径格式",
      description: "传入包含文件名的路径\n示例：/data/storage/el2/base/haps/entry/files/photo.jpg",
      options: { path: "/data/storage/el2/base/haps/entry/files/photo.jpg" },
      expected: 'SUCCESS'
    },
    {
      id: 5,
      title: "5. 空路径",
      description: "传入空字符串路径",
      options: { path: "" },
      expected: 'FAILURE'
    },
    {
      id: 6,
      title: "6. 传入多个///目录",
      description: "传入多个///目录",
      options: { path: "/data/storage/el2/base/haps/entry/files//////////////" },
      expected: 'SUCCESS'
    },
    {
      id: 7,
      title: "7. 特殊字符路径",
      description: "路径包含中文和特殊字符\n(测试编码处理/storage/@#$%^&/)",
      options: { path: "/data/storage/el2/base/测试编码处理/storage/@#$%^&/" },
      expected: 'FAILURE'
    },
    {
      id: 8,
      title: "8. 超长路径名",
      description: "路径长度超过系统限制\n(通常255字符)",
      options: {
        path: "/data/storage/el2/base/" + "a".repeat(240) + "/"
      },
      expected: 'SUCCESS'
    },
    {
      id: 9,
      title: "9. 带空格路径",
      description: "路径包含空格字符",
      options: { path: "/data/storage/el2/base/My Photos/" },
      expected: 'SUCCESS'
    },
  ];

  const runTest = async (testCase: PathTestCase) => {
    setActiveTest(testCase);
    setErrorMessage(null);

    try {
      const photo = await camera.current?.takePhoto(testCase.options);
      if (photo) {
        const result: TestResult = {
          test: testCase,
          result: [
            `✅ 拍照成功 (预期: ${testCase.expected})`,
            `📁 返回路径: ${photo.path}`,
            `🖼️ 尺寸: ${photo.width}x${photo.height}`,
            testCase.expected === 'FAILURE'
              ? `⚠️ 预期失败但成功，请检查实现逻辑`
              : `✔️ 符合预期成功`
          ].join('\n'),
          photo: {
            path: photo.path,
            width: photo.width,
            height: photo.height
          }
        };
        setCurrentResult(result);
      }
    } catch (error) {
      const result: TestResult = {
        test: testCase,
        result: [
          `❌ 拍照失败 (预期: ${testCase.expected})`,
          `💡 错误信息: ${error.message}`,
          testCase.expected === 'SUCCESS'
            ? `⚠️ 预期成功但失败，请检查路径权限`
            : `✔️ 符合预期失败`
        ].join('\n')
      };
      setCurrentResult(result);
    }
  };

  const toggleMirror = () => setIsMirrored(prev => !prev);
  const clearResult = () => setCurrentResult(null);
  const toggleCamera = () => {
    setCameraPosition(prev => (prev === 'front' ? 'back' : 'front'));
  };
  const onError = (error) => {
    setErrorMessage(error.message);
  }

  return (
    <View style={styles.container}>
      <View style={styles.cameraContainer}>
        <Camera
          style={StyleSheet.absoluteFill}
          ref={camera}
          device={device}
          format={format}
          isActive={true}
          photo={true}
          isMirrored={isMirrored}
          onError={onError}
        />
      </View>

      <View style={styles.controlContainer}>
        {errorMessage && (
          <View style={styles.errorContainer}>
            <Text style={styles.errorText}>⚠️ 相机错误: {errorMessage}</Text>
          </View>
        )}

        <View style={styles.mirrorControl}>
          <Button
            title={isMirrored ? '关闭镜像' : '开启镜像'}
            onPress={toggleMirror}
          />
          <Button
            title="前后摄像头切换"
            onPress={toggleCamera}
          />
          <Button
            title="清空结果"
            onPress={clearResult}
            color="#F44336"
          />
        </View>

        <ScrollView
          horizontal
          style={styles.testButtonsContainer}
          showsHorizontalScrollIndicator={false}
        >
          {testCases.map(test => (
            <View key={test.id} style={styles.testButton}>
              <Button
                title={test.title}
                onPress={() => runTest(test)}
                color={activeTest?.id === test.id ? '#4CAF50' : '#2196F3'}
              />
            </View>
          ))}
        </ScrollView>

        {currentResult && (
          <View style={styles.resultContainer}>
            <Text style={styles.resultTitle}>{currentResult.test.title}</Text>
            <Text style={[
              styles.resultText,
              currentResult.result.includes('✅') ? styles.successText : styles.errorText
            ]}>
              {currentResult.result}
            </Text>

            {currentResult.photo && (
              <View style={styles.photoPreview}>
                <Text style={styles.previewText}>图片预览:</Text>
                <Image
                  source={{ uri: `file://${currentResult.photo.path}` }}
                  style={styles.previewImage}
                  resizeMode="contain"
                />
                <Text style={styles.photoInfo}>
                  尺寸: {currentResult.photo.width}x{currentResult.photo.height}
                </Text>
              </View>
            )}
          </View>
        )}
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#000',
  },
  cameraContainer: {
    height: 400,
    flex: 1,
  },
  controlContainer: {
    height: '60%',
    padding: 12,
  },
  mirrorControl: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginBottom: 10,
  },
  testButtonsContainer: {
    height: 200,
    marginBottom: 10,
  },
  testButton: {
    marginRight: 8,
  },
  errorContainer: {
    backgroundColor: 'rgba(244, 67, 54, 0.2)',
    padding: 8,
    borderRadius: 4,
    marginBottom: 10,
    borderLeftWidth: 3,
    borderLeftColor: '#F44336',
  },
  errorText: {
    color: '#FFCDD2',
    fontSize: 12,
  },
  resultContainer: {
    flex: 1,
    padding: 10,
    backgroundColor: 'rgba(255,255,255,0.1)',
    borderRadius: 5,
    marginBottom: 250,
  },
  resultTitle: {
    color: '#2196F3',
    fontWeight: 'bold',
    fontSize: 14,
    marginBottom: 5,
  },
  resultText: {
    color: 'white',
    fontSize: 12,
    marginBottom: 10,
  },
  successText: {
    color: '#4CAF50',
  },
  photoPreview: {
    marginTop: 10,
    alignItems: 'center',
  },
  previewText: {
    color: 'white',
    fontSize: 12,
    marginBottom: 5,
  },
  previewImage: {
    width: 150,
    height: 150,
    borderWidth: 1,
    borderColor: '#555',
  },
  photoInfo: {
    color: '#AAA',
    fontSize: 10,
    marginTop: 2,
  },
});